<template>
  <el-dialog title="选择部门" width="25%" append-to-body draggable 
              :close-on-click-modal="false" v-model="visible">
    <div style="padding-bottom: 10px;">
      <el-input v-model="filterTreeText" placeholder="请输入关键字" />
    </div>
    <div style="height: 260px">
      <el-scrollbar>
        <el-tree
          node-key="id"
          class="filter-tree"
          :props="props"
          :data="tdata"
          v-loading.lock="loading"
          empty-text="木有数据~"
          element-loading-text="拼命加载中"
          :expand-on-click-node="false"
          default-expand-all
          :current-node-key="selectId"
          :filter-node-method="filterTreeNode"
          ref="treeRef"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }} - [{{ data.attributes && data.attributes.code }}]&nbsp;&nbsp;</span>
            </span>
          </template>
        </el-tree>
      </el-scrollbar>
    </div>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirmChoice()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import http from "@/utils/httpRequest";
import { ref, watch, onMounted, defineExpose, defineEmits } from "vue";

import { ElTree, ElMessage } from 'element-plus';

// 弹窗是否显示
const visible = ref(false);

// 当前选中节点
const selectId = ref("");

// 部门树形结构数据
const tdata = ref([]);

// 是否正在加载
const loading = ref(false);

// 部门树默认属性
const props = {
  label: "name",
  children: "children",
};

// 菜单树过滤文本
const filterTreeText = ref("");

// 部门树引用
const treeRef = ref<InstanceType<typeof ElTree>>();

// 父级组件的自定义事件
const emit = defineEmits([ 'selectDepartEvent' ]);

// 监听查询内容变化
watch(filterTreeText, (n, o) => {
  treeRef.value!.filter(n)
});

// 组件挂载完成后执行
onMounted(() => {
  initTreeData();
});

// 初始化
const init = (action, id) => {
  visible.value = true;
  selectId.value = id;
};

// 加载树形菜单
const initTreeData = () => {
  loading.value = true;
  http
    .get({
      url: "/depart/tree",
    })
    .then(({ data }) => {
      if (http.success(data)) {
        tdata.value = data.body;
      }
      loading.value = false;
    });
};

// 确认选择
const confirmChoice = () => {
  let node = treeRef.value.getCurrentNode()
  if (!node) {
    ElMessage.error('请选择部门！');
    return;
  }
  emit('selectDepartEvent', node);
  visible.value = false;
};

// 过滤菜单
const filterTreeNode = (value, data) => {
  if (!value) {
    return true;
  }
  return data.name.indexOf(value) !== -1;
};

// 暴露方法
defineExpose({ init });
</script>
